package com.example.shiroredisdemo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Author: Anita
 * @Date: Created in 19:04 2018/1/6
 */
@Slf4j
public final class SerializeUtils {

    public static Object deserialize(byte[] bytes){
        Object result = null;
        if(isEmpty(bytes)){
            return null;
        }
        try{
            ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
            try{
                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
                try{
                    result = objectInputStream.readObject();
                }catch(ClassNotFoundException e){
                    throw new Exception("Failed to deserialize object type",e);
                }
            }catch(Throwable e){
                throw new Exception("Failed to deserialize",e);
            }
        }catch(Exception e){
            log.error("Failed to deserizlize",e);
        }

        return result;
    }

    public static boolean isEmpty(byte[] data){
        return data ==null || data.length == 0;
    }

    public static byte[] serialize(Object object){
        byte[] result = null;
        if(object==null){
            return new byte[0];
        }
        try{
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
            try{
                if(!(object instanceof Serializable)){
                    throw new IllegalArgumentException(
                            SerializeUtils.class.getSimpleName()+"requires a Serializeble payload"
                                    +"but received an object of type["+object.getClass().getName()+"]"
                    );
                }
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
                objectOutputStream.writeObject(object);
                objectOutputStream.flush();
                result = byteStream.toByteArray();
            }catch(Throwable ex){
                throw new Exception("Failed to serialize",ex);
            }
        }catch(Exception e){
            log.error("Failed to serialize",e);

        }
        return result;
    }
}